<script setup>
import { User, Lock, Iphone } from '@element-plus/icons-vue'
import { userRegisterService } from '@/api/user'
import { userLoginService } from '@/api/user'
import { adminLoginService } from '@/api/admin'
import { ref, watch, onMounted } from 'vue'
const isRegister = ref(false)
//定义年龄数据验证的函数
const ageRangeRule = (minAge, maxAge) => ({
  validator(rule, value) {
    const age = parseInt(value, 10)
    // if (isNaN(age)) {
    //   return Promise.reject('请输入正确的年龄')
    // }
    if ((age !== '' && age < minAge) || age > maxAge) {
      return Promise.reject(`年龄必须在${minAge}岁和${maxAge}岁之间`)
    }
    return Promise.resolve()
  }
})
//注册的数据收集
const formModel = ref({
  name: '',
  password: '',
  phone: '',
  address: '',
  sex: '',
  age: ''
})
const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '请输入有效的手机号',
      trigger: 'blur'
    }
  ],
  age: [ageRangeRule(18, 70)]
}
//记住我
const selectRe = ref()
//用来表单整体预校验的
const form = ref()

//注册请求
const register = async () => {
  await form.value.validate()
  if (formModel.value.address) {
    const res = await userRegisterService(formModel.value)
    if (res.data.status == 200) {
      ElMessage.success(res.data.message)
      isRegister.value = false
    } else {
      ElMessage.error(res.data.message)
    }
  } else {
    ElMessage.error('注册失败，请选择完整的地址信息')
  }

  //isRegister.value = false
}
//登录请求
import { useUserStore } from '@/stores/index'
import { adminUserStore } from '@/stores/index'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const adminStore = adminUserStore()
const IdChecked = ref('1')
//登录
const login = async () => {
  await form.value.validate()
  if (selectRe.value) {
    // 如果勾选了记住密码，则将用户名和密码保存到本地存储中
    localStorage.setItem('name', formModel.value.name)
    localStorage.setItem('password', formModel.value.password)
  } else {
    // 否则清除本地存储中的用户名和密码
    localStorage.removeItem('username')
    localStorage.removeItem('password')
  }
  localStorage.removeItem('loggedIn') //清空通知存储
  if (IdChecked.value === '1') {
    //拿到返回的数据
    const res = await userLoginService(formModel.value)
    //存到本地仓库token值
    //res.data是自己加上去的
    if (res.data.status == 200) {
      userStore.setToken(res.data.token)
      ElMessage.success(res.data.message)
      router.push('/user')
    } else {
      ElMessage.error('登录失败，账号或密码不对')
    }
  } else {
    //管理员登录

    const res = await adminLoginService(formModel.value)

    if (res.data.status === 200) {
      const { token, message } = res.data

      adminStore.setToken(token)
      router.push('/admin')
      ElMessage.success(message)
    } else {
      ElMessage.error('登录失败，账号或密码不对')
    }
  }
}
// 在页面加载时，从本地存储中读取用户名和密码
onMounted(() => {
  const savedName = localStorage.getItem('name')
  const savedPassword = localStorage.getItem('password')
  if (savedName && savedPassword) {
    formModel.value.name = savedName
    formModel.value.password = savedPassword
    selectRe.value = true
  }
})
//注册成功后重置信息
watch(isRegister, () => {
  formModel.value = {
    name: '',
    password: '',
    phone: '',
    address: '',
    sex: '',
    age: ''
  }
  clearAdress()
})
const baiduPrivice = ref()
import axios from 'axios'
//监听切换注册的事件后触发获取百度数据
watch(isRegister, (newValue) => {
  if (newValue === true && baiduPrivice.value === undefined) {
    axios
      .get(
        'api_region_search/v1/?keyword=中国&sub_admin=3&ak=nqSAq8S0isAO5oeDnN6S3amqh9SB2aMP'
      )
      .then((response) => {
        baiduPrivice.value = response.data.districts[0].districts

        console.log(baiduPrivice.value[0].districts)
      })
      .catch((error) => {
        console.error(error)
      })
    //
  }
})

//根据省份，获取城市的处理
const baiduCity = ref()
const selectProvice = ref({
  index: ''
})
const isDisabled = ref({
  values: 'true'
})
const befisDisabled = ref({
  values: false
})
const handleSelectProviceChange = () => {
  //ElMessage.success(label)
  if (selectProvice.value.index !== '') {
    //formModel.value.address = `${baiduPrivice.value[selectProvice.value.index].name} `
    baiduCity.value = baiduPrivice.value[selectProvice.value.index].districts
    isDisabled.value.values = false
    befisDisabled.value.values = true
  }
}

//根据城市，获取区的处理
const isDisabled1 = ref({
  //记录选择的状态
  values: 'true'
})
const baiduCityBelong = ref() //把上一次数据把一层对象
const selectCity = ref({
  //记录上一个选择器选择的下标选择的状态
  index: ''
})
const befisDisabled1 = ref({
  values: false
})
const handleSelectCityChange = () => {
  //点击选择后的逻辑
  if (selectCity.value.index !== '') {
    //formModel.value.address = baiduPrivice.value[selectProvice.value.index].name //再次复制
    //formModel.value.address = `${`${baiduPrivice.value[selectProvice.value.index].name} `}${baiduCity.value[selectCity.value.index].name} `
    baiduCityBelong.value = baiduCity.value[selectCity.value.index].districts //传值下去
    isDisabled1.value.values = false
    isDisabled.value.values = true
    befisDisabled1.value.values = true
  }
}
//市/区/县的处理
const selectCityBelong = ref({
  //记录上一个选择器选择的下标选择的状态
  index: ''
})
const handleSelectCityBelongChange = () => {
  if (selectCity.value.index !== '') {
    //formModel.value.address = `${formModel.value.address}${baiduCity.value[selectCity.value.index].name}` //上次选值
    formModel.value.address = `${`${`${baiduPrivice.value[selectProvice.value.index].name} `}${baiduCity.value[selectCity.value.index].name} `}${baiduCityBelong.value[selectCityBelong.value.index].name} ` //变动的值加上去
    detailAdressMid.value.value = formModel.value.address //不要污染formModel.value.address
    isDisabled1.value.values = true
    isDisabled2.value.values = false
  }
}
//详细地址的处理
const detailAdress = ref({
  value: ''
})
const detailAdressMid = ref({
  value: ''
})
const isDisabled2 = ref({
  values: true
})
const handleDetailAdressInput = () => {
  //detailAdressMidvalue.value.address = ''

  formModel.value.address = detailAdressMid.value.value
  formModel.value.address = `${`${`${`${baiduPrivice.value[selectProvice.value.index].name} `}${baiduCity.value[selectCity.value.index].name} `}${baiduCityBelong.value[selectCityBelong.value.index].name} `}${detailAdress.value.value}`
  isDisabled2.value.values = true
  console.log(formModel.value.address)
}
//地址清除功能
const clearAdress = () => {
  selectProvice.value.index = ''
  selectCity.value.index = ''
  selectCityBelong.value.index = ''
  detailAdress.value.value = ''
  formModel.value.address = ''
  isDisabled.value.values = true
  befisDisabled.value.values = false
  isDisabled1.value.values = true
  isDisabled2.value.values = true
}
</script>
<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="8" :offset="2" class="form">
      <!-- 注册相关表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="name" label="(必填)" required>
          <el-input
            v-model="formModel.name"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" label="(必填)" required>
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="(必填)" required>
          <el-input
            v-model="formModel.phone"
            :prefix-icon="Iphone"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label=" 地&nbsp;&nbsp;址" required>
          <el-select
            style="width: 110px"
            v-model="selectProvice.index"
            @change="handleSelectProviceChange"
            placeholder="省份"
            :disabled="befisDisabled.values"
          >
            <el-option
              v-for="(item, index) in baiduPrivice"
              :key="index"
              :label="item.name"
              :value="index"
            ></el-option>
          </el-select>

          <el-select
            style="width: 120px; margin-left: 1px"
            :disabled="isDisabled.values"
            placeholder="市/区/州"
            v-model="selectCity.index"
            @change="handleSelectCityChange"
          >
            <el-option
              v-for="(item, index) in baiduCity"
              :key="index"
              :label="item.name"
              :value="index"
            ></el-option>
          </el-select>

          <el-select
            style="width: 150px; margin-left: 1px"
            placeholder="市/区/县/乡/镇"
            :disabled="isDisabled1.values"
            v-model="selectCityBelong.index"
            @change="handleSelectCityBelongChange"
          >
            <el-option
              v-for="(item, index) in baiduCityBelong"
              :key="index"
              :label="item.name"
              :value="index"
            ></el-option>
          </el-select>

          <el-input
            placeholder="详细地址"
            style="margin-top: 20px; width: 310px"
            v-model="detailAdress.value"
            @change="handleDetailAdressInput"
            :disabled="isDisabled2.values"
          ></el-input>
          <el-button
            type="primary"
            style="width: 90px; margin-left: 4px; margin-top: 20px"
            @click="clearAdress"
            >清空地址信息</el-button
          >
        </el-form-item>
        <el-form-item label="性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别">
          <el-radio-group v-model="formModel.sex">
            <el-radio :label="1" :value="男" style="margin-right: 50px"
              >男
            </el-radio>
            <el-radio :label="2" :value="女">女</el-radio>
          </el-radio-group>
          <el-form-item
            prop="age"
            style="margin-left: auto"
            label="年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;龄"
          >
            <el-input
              v-model="formModel.age"
              type="number"
              min="18"
              max="70"
              style="width: 120px"
            ></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" @click="isRegister = false"> ← 返回 </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录相关表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <h1 style="align-items: center">登录</h1>

        <el-form-item prop="name">
          <el-input
            v-model="formModel.name"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox
              v-model="selectRe"
              label="记住我"
              size="large"
              border
            />
            <el-radio-group v-model="IdChecked">
              <el-radio label="1" size="large" border style="margin-right: 50px"
                >用户登录</el-radio
              >
              <el-radio label="2" size="large" border>管理员登录 </el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="login"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" @click="isRegister = true"> 注册 → </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background: url('@/assets/login_bg.jpg') no-repeat center;
    border-radius: 0 20px 20px 0;
    width: 800px;
    height: 700px;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    margin-bottom: 8px; /* 设置下边距 */
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
